<template>
  <div>
    <van-nav-bar title="地址管理" left-arrow @click-left='$router.back()'>
      <template #right>
        <van-icon name="ellipsis" />
      </template>
    </van-nav-bar>
    <!-- //地址列表 -->
    <van-address-list
  v-model="address.chosenAddressId" :list="address.list" disabled-text="以下地址超出配送范围"
  default-tag-text="默认"
  @add="onAdd"
  @edit="onEdit"
  @click-item="goCreateOrder"
  />
</div>
</template>

<script setup>
import { reactive, onMounted } from 'vue';
import { getAddressList } from '../../api/index.js';
import { useRouter } from 'vue-router';
import { showConfirmDialog } from 'vant';


let router = useRouter();
let address = reactive({
  list: [],
  chosenAddressId: '',
  isEdit: true
});
let onAdd = () => {
  router.push('/addressEdit')
}
let onEdit = (item) => {
  router.push('/addressEdit?addressId=' + item.id)
  address.isEdit = false;
}
let goCreateOrder = (item) => {
  if (!address.isEdit) {
    address.isEdit = true;
    return;
  }
  // console.log('生成订单');
  showConfirmDialog({
    title: '确认地址',
    message:'是否确认此地址'
  }).then(() => {
    router.push({
      path: "/createOrder",
      query:{ addressId: item.id }

    })
  })
}

onMounted(() => {
  getData().then(() => {
    let res = address.list.filter(item => item.isDefault == true)
    console.log(res);
    address.chosenAddressId = res[0].id
  })
})

async function getData() {
  await getAddressList().then((res => {
    console.log(res);
    address.list = res.data.map(item => {
      return {
        id: item.addressId,
        name: item.userName,
        tel:item.userPhone,
        address: item.provinceName + item.cityName + item.regionName + item.detailAddress,
        isDefault: item.defaultFlag
      }
    })
  }))
}

</script>

<style lang="scss" scoped>

</style>